<template>
  <div >
     <!-- top -->

     <div style="width: 1100px;margin-left: 180px;padding-top: 20px;">
         <!-- 图标 -->
         <div style="">
            <img
            style="width: 140px; height: 50px"
            src="@/static/logo.png"
            alt=""
             />
          </div>

    <el-card  class="address-card">
      <div slot="header" class="clearfix">
        <span>新增收货地址</span>
      </div>
      <el-form
        :model="addressForm"
        :rules="rules"
        ref="addressForm"
        label-width="120px"
        class="address-form"
      >
        <el-form-item label="收件人姓名" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收件人姓名"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addressForm.phone" maxlength="11" placeholder="请输入11位手机号码"></el-input>
        </el-form-item>

        <el-form-item label="所在地区" props="regin">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"

            placeholder="请选择省/市/区"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="详细地址" prop="detail">
          <el-input
            type="textarea"
            v-model="addressForm.detail"
            placeholder="请输入详细地址信息"
            :rows="3"
          ></el-input>
        </el-form-item>

        <el-form-item label="设为默认地址" prop="isDefault">
          <el-switch v-model="addressForm.isDefault"></el-switch>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('addressForm')">保存地址</el-button>
          <el-button @click="resetForm('addressForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  </div>
</template>

<script>

import { areaList } from '@/utils/area-data/dist/index.cjs.js'
import { formatAddress } from '@/utils/formatAddress.js'
import { addAddress } from '@/api/address.js'
export default {

  data () {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号码'))
      }
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }

    return {
      addressForm: {
        name: '',
        phone: '',
        region: [],
        detail: '',
        isDefault: 0

      },
      rules: {
        name: [
          { required: true, message: '请输入收件人姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        region: [
          { type: 'array', required: true, message: '请选择所在地区', trigger: 'change' }
        ],
        detail: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
          { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
        ]
      },
      regionOptions: [
        {
          value: '省级编码',
          label: '省级名称',
          children: [
            {
              value: '市级编码',
              label: '市级名称',
              children: [
                { value: '区级编码', label: '区级名称' }
              ]
            }
          ]
        }
      ]
    }
  },
  created () {
    // 格式化地址
    this.regionOptions = formatAddress(areaList)
    console.log(this.regionOptions)
  },
  methods: {

    // 格式化地址

    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$message({
            message: '地址保存成功',
            type: 'success'
          })

          // 这里可以添加提交到后端的逻辑

          // 获取完整地址字符串
          const fullAddress = this.getFullRegionName(this.addressForm.region)
          console.log(fullAddress, 'fullAddress')
          this.addressForm.region = fullAddress
          if (this.addressForm.isDefault === false) {
            this.addressForm.isDefault = 0
          }
          if (this.addressForm.isDefault === true) {
            this.addressForm.isDefault = 1
          }
          //  this.addressForm.isDefault = this.addressForm.isDefault ? 1 : 0
          console.log('提交数据:', this.addressForm)
          const res = addAddress(this.addressForm)

          console.log(res)
          this.$message({
            message: '地址添加成功',
            type: 'success'
          })
          this.$router.push('/order')
        } else {
          this.$message.error('请填写完整信息')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 获取完整地区名称的方法
    getFullRegionName (regionCodes) {
      if (!regionCodes || !this.regionOptions) return ''

      const names = []
      let currentLevel = this.regionOptions

      // 递归查找各级名称
      regionCodes.forEach(code => {
        const found = currentLevel.find(item => item.value === code)
        if (found) {
          names.push(found.label)
          currentLevel = found.children || []
        }
      })

      return names.join('')
    }
  }
}

</script>

<style scoped>

.address-container {
  width: 1100px;
  margin: 0 auto;
  padding: 20px;

}

.address-card {
  width: 100%;
  margin-top: 20px;

}

.address-form {
  width: 80%;
  margin: 0 auto;

}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>
